﻿#region Copyright 2008 - Evolution Systems.
//
// Author: José Rogério Ferreira dos Santos(joserogerio.santos@gmail.com)
//
// All rights are reserved. Reproduction or transmission in whole or in part, in
// any form or by any means, eletronic, mechanical or otherwise, is prohibited
// without the prior written permission of the author.
//
// Filename: frmRegisterPerson.cs
#endregion

using System;
using System.Drawing;
using System.Windows.Forms;
using ComponentFactory.Krypton.Toolkit;

namespace csharp.rad.general
{
	/// <summary>
	/// Description of frmRegisterPerson.
	/// </summary>
	public partial class frmRegisterPerson : csharp.common.RegisterTemplate
	{
		#region protected declarations
			protected Person person = new Person();
			protected Address address1 = new Address();
			
			protected Phone phone1 = new Phone();
			protected Phone phone2 = new Phone();
			protected Phone phone3 = new Phone();
			
			protected TType type  = new TType();

		
			//Lists
			protected Persons listPerson;
			protected Statuss listPersonStatus;
			protected Types listPhoneTypes;
			protected Countries listCountries;
			protected States listStates;
			protected Cities listCities;
			protected Neighborhoods listNeighborhoods;
			
			protected bool mutexCountry= false;
			protected bool mutexState  = false;
			protected bool mutexCity   = false;		
		#endregion
		
		public frmRegisterPerson()
		{
			resizeForm = true;
			this.Text= "teste";
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			
			listPerson		  = new Persons();
			listPersonStatus = new Statuss();
			listPhoneTypes   = new Types();
			listCountries    = new Countries();
			listStates  	  = new States();
			listCities		  = new Cities();
			listNeighborhoods= new Neighborhoods();
		}
			
		#region overrided methods		
			protected override void newEvent()
			{
				person.clear();
				address1.clear();
				phone1.clear();
				phone2.clear();
				phone3.clear();
				
				dtpBornDate.Text = DateTime.Today.AddYears(-25).ToString("dd/MM/yyyy");
				txtCode.Focus();
			}
			
			/// <summary>
			/// Set data from edits to class
			/// </summary>
			protected override void setClass()
			{			
				person.companyId 				= Information.companyId;
				person.name						= txtName.Text;
				person.nickname				= txtNickname.Text;
				person.cpfCnpj					= txtCpf.Text;
				person.rgIe				   	= txtRg.Text;
				person.bornDate				= dtpBornDate.Text;	
				person.nationality			= txtNationality.Text;
				person.naturalness			= txtNaturalness.Text;
				person.maritalStatus			= cmbMaritalStatus.Text;
				if (rdbMasc.Checked)
					person.sex= "M";
				else
					person.sex= "F";
				
				person.email					= txtEmail.Text;
				//person.status
				person.enable 					= chkEnable.Checked;
				person.code						= txtCode.Text;
				person.nameResponsable		= txtResponsableName.Text;
				person.documentResponsable	= txtResponsableDoc.Text;	
				//person.username				
				//person.password				
				//person.person_id			
				//person.type_id				
				person.webPage					= txtWebPage.Text;
				person.obs						= txtObs.Text;
				//person.update_date			
				person.juridic					= rdbJuridic.Checked;
				
				//Set Address
				type.get("address","001"); //Residencial
				address1.address 				= txtAddress1Address.Text;
				address1.neighborhoodId 	= (cmbAddress1Neighborhoods.SelectedItem as Neighborhood).id;
				address1.typeId				= type.id;
				address1.complement			= txtAddress1Complement.Text;
				address1.reference			= txtAddress1Reference.Text;
				address1.number				= txtAddress1Number.Text;
				address1.enable				= chkAddress1Enable.Checked;
				
				//Set Phones
				if (cmbPhone1Type.SelectedIndex >= 0)
				{
					phone1.ddd 					= txtPhone1DDD.Text;
					phone1.number				= txtPhone1Number.Text;
					phone1.branch				= txtPhone1Branch.Text;
					phone1.typeId				= (cmbPhone1Type.SelectedItem as TType).id;
					phone1.count = "1";
				}
				
				if (cmbPhone2Type.SelectedIndex >= 0)
				{
					phone2.ddd 					= txtPhone2DDD.Text;
					phone2.number				= txtPhone2Number.Text;
					phone2.branch				= txtPhone2Branch.Text;
					phone2.typeId				= (cmbPhone2Type.SelectedItem as TType).id;
					phone2.count = "2";
				}
				
				if (cmbPhone3Type.SelectedIndex >= 0)
				{
					phone3.ddd 					= txtPhone3DDD.Text;
					phone3.number				= txtPhone3Number.Text;
					phone3.branch				= txtPhone3Branch.Text;
					phone3.typeId				= (cmbPhone3Type.SelectedItem as TType).id;
					phone3.count = "3";
				}				
			}
			
			/// <summary>
			/// Set data from class to edits
			/// </summary>
			protected override void setEdits()
			{
				person.id = dgvMain.CurrentRow.Cells["id"].Value.ToString();
				
				if (person.get())
				{
					fillEdits();
				}
			}
			
			protected void fillEdits()
			{
					txtName.Text 			= person.name;
					txtNickname.Text     = person.nickname;
					txtCpf.Text				= person.cpfCnpj;
					txtRg.Text				= person.rgIe;
					dtpBornDate.Text		= person.bornDate;
					txtNationality.Text	= person.nationality;
					txtNaturalness.Text 	= person.naturalness;
					cmbMaritalStatus.Text= person.maritalStatus;
					if (person.sex.Equals("M"))
						rdbMasc.Checked= true;
					else
						rdbFem.Checked= true;
					txtEmail.Text			= person.email;
					//status
					chkEnable.Checked		= person.enable;
					txtCode.Text			= person.code;
					txtResponsableName.Text= person.nameResponsable;
					txtResponsableDoc.Text = person.documentResponsable;
					//username
					//password
					//person_id
					//type_id
					txtWebPage.Text		= person.webPage;
					txtObs.Text				= person.obs;
					if (person.juridic)
						rdbJuridic.Checked= true;
					else
						rdbFisic.Checked = true;
					
					//Address					
					type.get("address","001"); //Residencia

					if (address1.get(person.id, type.id))
					{
						listNeighborhoods.search(address1.neighborhoodId);
						
						txtAddress1Address.Text		=  address1.address; 
						cmbAddress1Neighborhoods.SelectedIndex=  listNeighborhoods.getIndex();
						//address.typeId				
						txtAddress1Complement.Text	=  address1.complement; 
						txtAddress1Reference.Text	=  address1.reference; 
						txtAddress1Number.Text		=  address1.number; 
						chkAddress1Enable.Checked	= 	address1.enable;
						txtAddress1ZipCode.Text    = listNeighborhoods.get().zipCode;
					}
					
					//Phones
					phone1.get(person.id, "1");
					if (!phone1.typeId.Equals(String.Empty))
					{
						txtPhone1DDD.Text				= phone1.ddd;
						txtPhone1Number.Text			= phone1.number;
						txtPhone1Branch.Text			= phone1.branch;
						Functions.setSelectedIndexComboTypes(cmbPhone1Type, phone1.typeId);
					}
					
					phone2.get(person.id, "2");
					if (!phone2.typeId.Equals(String.Empty))
					{
						txtPhone2DDD.Text				= phone2.ddd;
						txtPhone2Number.Text			= phone2.number;
						txtPhone2Branch.Text			= phone2.branch;
						Functions.setSelectedIndexComboTypes(cmbPhone2Type, phone2.typeId);
					}
					
					phone3.get(person.id, "3");
					if (!phone3.typeId.Equals(String.Empty))
					{
						txtPhone3DDD.Text				= phone3.ddd;
						txtPhone3Number.Text			= phone3.number;
						txtPhone3Branch.Text			= phone3.branch;
						Functions.setSelectedIndexComboTypes(cmbPhone3Type, phone3.typeId);
					}					
			}
			
			/// <summary>
			/// Fill the DataGridView
			/// </summary>
			protected override void fillDataGridView()
			{
				int tam;
				//TODO: Nao listar todos as pessoas ao iniciar
				listPerson.fillList();
				
				tam = listPerson.count();
				dgvMain.Rows.Clear();
				for (int i=0; i < tam; i++)
				{
					dgvMain.Rows.Add(new String[] {listPerson.get(i).id, 
					                 					 listPerson.get(i).code,
					                 					 listPerson.get(i).name,
					                 					 listPerson.get(i).cpfCnpj});
				}				
			}
			
			/// <summary>
			/// Find the object of search
			/// </summary>
			protected override void find()
			{
				common.Util.searchInGrid(dgvMain, "name", txtSearch.Text);
			}		
			
		   /// <summary>
		   /// Save the register in the database.
		   /// </summary>
		   /// <returns>bool - true if the register was saved sucessful, false case not.</returns>	
		   protected override bool save()
		   {
		   	//TODO: Retirar, iniciar transacao no form que herdar desse.
		   	//common.Database.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
		   	
		   	if( !person.save() )
		   	{
		   		//common.Database.RollBack();
		   		return false;
		   	}
		   		
		   	address1.personId = person.id;
		   	if( !address1.save() )
		   	{
		   		//common.Database.RollBack();
		   		return false;
		   	}
		   	
		   	phone1.personId = person.id;
		   	phone2.personId = person.id;
		   	phone3.personId = person.id;		   	
		   	if (!phone1.typeId.Equals(String.Empty))
		   		if (!phone1.store())
		   		{
		   			//common.Database.RollBack();
		   			return false;
		   		}
		   	
		   	if (!phone2.typeId.Equals(String.Empty))
		   		if (!phone2.store())
		   		{
		   			//common.Database.RollBack();
		   			return false;
		   		}
		   	
		   	if (!phone3.typeId.Equals(String.Empty))
		   		if (!phone3.store())
		   		{
		   			//common.Database.RollBack();
		   			return false;
		   		}		
		   	
		   	//UNDONE	
		   	//common.Database.Commit();
		   	
		   	return true;
		   }
		   
		   /// <summary>
		   /// Update the register in the database
		   /// </summary>
		   /// <returns>bool - true if the register was updated sucessful, false case not.</returns>
		   protected override bool update()
		   {   
		   	if (!person.update())
		   		return false;
		   	
		   	if (!address1.update())
		   		return false;
		   	
		   	phone1.personId = person.id;
		   	phone1.count    = "1";
		   	phone2.personId = person.id;
		   	phone2.count    = "2";
		   	phone3.personId = person.id;
		   	phone3.count    = "3";
		   	if (!phone1.typeId.Equals(String.Empty))
		   		if (!phone1.store())
		   			return false;
		   	
		   	if (!phone2.typeId.Equals(String.Empty))
		   		if (!phone2.store())
		   			return false;
		   	
		   	if (!phone3.typeId.Equals(String.Empty))
		   		if (!phone3.store())
		   			return false;
		   	
		   	return true;
		   }
		   
		   /// <summary>
		   /// Delete the register in the database.
		   /// </summary>
		   /// <returns>bool - true if the register was deleted sucessful, false case not.</returns>
		   protected override bool delete()
		   {
		   	person.id = dgvMain.CurrentRow.Cells["id"].Value.ToString();
		   	
		   	return person.delete();
		   	
		   	//Cascade no address, hehehehheheh
		   	
		   	//Cascade no supplier, se houver
		   	
		   	//Cascade no phone, muahmuahmuahmuah <- gargalhada fatal.:D
	
		   }
		   
		   /// <summary>
		   /// Method call in initialization
		   /// </summary>
		   protected override void init()
		   {
		   	//dgvMain.Size.Width = 803; 
		   	//dgvMain.Size.Height= 423;
		   	
		   	DataGridViewTextBoxColumn id 		 = new DataGridViewTextBoxColumn();
		   	DataGridViewTextBoxColumn code 	 = new DataGridViewTextBoxColumn();
		   	DataGridViewTextBoxColumn name 	 = new DataGridViewTextBoxColumn();
		   	DataGridViewTextBoxColumn cpfCpnj = new DataGridViewTextBoxColumn();
		   	
		   	id.Name 			= "id";
		   	id.Visible		= false;
		   	
		   	code.Name 		= "code";
		   	code.HeaderText= "Código";
		   	
		   	name.Name 		= "name";
		   	name.HeaderText= "Nome";
		   	name.Width		= 300;
		   	
		   	cpfCpnj.Name	= "cpfCnpj";
		   	cpfCpnj.HeaderText= "CPF/CPNJ";
		   	
		   	dgvMain.Columns.AddRange(new DataGridViewColumn[] {id, code, name, cpfCpnj});
		   	
		   	listPhoneTypes.fillList("phone");
				fillCombosPhoneTypes();
				
				fillCombosAddress();
			}
		#endregion
		
		private void fillCombosAddress()
		{
				listCountries.fillList();
				Functions.fillComboCountries(listCountries, cmbAddress1Country, "id", "name");
				Functions.fillComboCountries(listCountries, txtNationality, "id", "name");
				
				listStates.fillList();
				Functions.fillComboStates(listStates, cmbAddress1State, "id", "name");
				
				listCities.fillList();
				Functions.fillComboCities(listCities, cmbAddress1City, "id", "name");
				
				listNeighborhoods.fillList();
				Functions.fillComboNeighborhoods(listNeighborhoods, cmbAddress1Neighborhoods, "id", "name");			
		}
		
		private void fillCombosPhoneTypes()
		{
			Functions.fillComboTypes(listPhoneTypes, cmbPhone1Type, "id","name");
			Functions.fillComboTypes(listPhoneTypes, cmbPhone2Type, "id","name");
			Functions.fillComboTypes(listPhoneTypes, cmbPhone3Type, "id","name");
		}
	   
	
		protected void CmbCountrySelectedValueChanged(object sender, EventArgs e)
		{
			if ((cmbAddress1Country.SelectedIndex >= 0) && (!mutexCountry))
			{
				cmbAddress1State.SelectedIndex = -1;
				cmbAddress1City.SelectedIndex  = -1;
				cmbAddress1Neighborhoods.SelectedIndex = -1;
				listStates.fillList((cmbAddress1Country.SelectedItem as Country).id);
				Functions.fillComboStates(listStates, cmbAddress1State, "id", "name");
			}	
			mutexCountry= false;
		}
		
		protected void CmbStateSelectedValueChanged(object sender, EventArgs e)
		{
			if (cmbAddress1State.SelectedIndex >= 0)
			{
				if (!mutexState)
				{
					cmbAddress1City.SelectedIndex = -1;
					cmbAddress1Neighborhoods.SelectedIndex = -1;
					listCities.fillList((cmbAddress1State.SelectedItem as State).id);
					Functions.fillComboCities(listCities, cmbAddress1City, "id", "name");
				}
				mutexCountry= true;
				//listStates.search((cmbAddress1State.SelectedItem as State).id);
				Functions.setSelectIndexComboCountries(cmbAddress1Country, (cmbAddress1State.SelectedItem as State).countryId); //listStates.get().countryId);
				mutexCountry= false;				
			}
			mutexState= false;
		}		
		
		
		protected void CmbCitySelectedValueChanged(object sender, EventArgs e)
		{
			if (cmbAddress1City.SelectedIndex >= 0)
			{
				if (!mutexCity)
				{
					cmbAddress1Neighborhoods.SelectedIndex= -1;
					listNeighborhoods.fillList((cmbAddress1City.SelectedItem as City).id);
					Functions.fillComboNeighborhoods(listNeighborhoods, cmbAddress1Neighborhoods, "id", "name");
				}
				mutexState= true;
				//listCities.search((cmbAddress1City.SelectedItem as City).id);
				Functions.setSelectIndexComboStates(cmbAddress1State, (cmbAddress1City.SelectedItem as City).stateId);// listCities.get().stateId);
				mutexState= false;				
			}
			mutexCity= false;
		}
		
		protected void CmbNeighborhoodsSelectedValueChanged(object sender, EventArgs e)
		{
			if (cmbAddress1Neighborhoods.SelectedIndex >= 0)
			{
				mutexCity= true;
				listNeighborhoods.search((cmbAddress1Neighborhoods.SelectedItem as Neighborhood).id);
				Functions.setSelectIndexComboCities(cmbAddress1City, listNeighborhoods.get().cityId);
				txtAddress1ZipCode.Text = listNeighborhoods.get().zipCode;
				mutexCity = false;
			}
		}
		
		public void TxtZipCodeLeave(object sender, EventArgs e)
		{
			if (!txtAddress1ZipCode.Equals(String.Empty))
			{
				if (listNeighborhoods.searchByZipCode(txtAddress1ZipCode.Text))
				{
					String id = listNeighborhoods.get().id;
					String cityId = listNeighborhoods.get().cityId;
					
					listNeighborhoods.fillList(cityId);
					Functions.fillComboNeighborhoods(listNeighborhoods, cmbAddress1Neighborhoods, "id", "name");
					
					Functions.setSelectIndexComboNeighborhoods(cmbAddress1Neighborhoods, id);
				}
			}
		}
		
		private void RdbJuridicCheckedChanged(object sender, EventArgs e)
		{
			if (rdbJuridic.Checked)
				txtCpf.Mask = "00.000.000/0000-00";
		}
		
		private void RdbFisicCheckedChanged(object sender, EventArgs e)
		{
			if (rdbFisic.Checked)
				txtCpf.Mask = "000.000.000-00";			
		}
		
		private void BtnAddNeighborhoodClick(object sender, EventArgs e)
		{
			frmRegisterNeighborhood form = new frmRegisterNeighborhood();
			
			try
			{
				form.ShowDialog();
				fillCombosAddress();
			}
			finally
			{
				form.Dispose();
			}
		}
	}
}
